// 发布订阅模式

// 发布调度中心
function PubSub () {
  this.uid = 0
  this.tokens = {}
  this.topics = {}

  this.publish = (topic, ...args) => {
    (this.topics[topic] || []).forEach(v => {
      v.subscriber(...args)
    })
  }
  this.subscribe = (topic, subscriber) => {
    if (this.topics[topic]) {
      // 不检查是否已经订阅过
      this.topics[topic].push({
        token: ++this.uid,
        subscriber: subscriber
      })
    } else {
      this.topics[topic] = [{
        token: ++this.uid,
        subscriber: subscriber
      }]
    }
    this.tokens[this.uid] = topic
    return this.uid
  }
  this.unsubscribe = (key) => {
    if (this.tokens[key]) {
      let topic = this.tokens[key]
      delete this.tokens[key]
      let i = this.topics[topic] ? this.topics[topic].findIndex(v => v.token === key) : -1
      i !== -1 && this.topics[topic].splice(i, 1)
    } else {
      delete this.topics[key]
    }
  }
}

export default PubSub
